<template>
    <div class="header-title">
        <img src="../../assets/icons/blackPeopleManage.svg" alt="icon" class="header-icon" />
        {{ title }}
        第 {{ currentIndex + 1 }} 个 / 共 {{ totalMembers }} 个成员 (请补充后提交！)
    </div>
    <el-form :model="form" label-width="auto" style="max-width: 1200px" ref="formRef" class="form-container">
        <!-- 基本信息 -->
        <el-row :gutter="20">
            <el-col :span="8">
                <el-form-item label="姓名" prop="name" :rules="[{ required: true, message: '姓名不能为空', trigger: 'blur' }]">
                    <el-input v-model="form.name" />
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="性别" prop="gender"
                    :rules="[{ required: true, message: '性别不能为空', trigger: 'blur' }]">
                    <el-select v-model="form.gender" placeholder="--性别--">
                        <el-option label="男" value="男"/>
                        <el-option label="女" value="女"/>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="身份证号码" prop="idCard"
                    :rules="[{ required: true, message: '身份证号码不能为空', trigger: 'blur' }]">
                    <el-input v-model="form.idCard" />
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter="20">
            <el-col :span="8">
                <el-form-item label="政治面貌" prop="politicalAffiliation"
                    :rules="[{ required: true, message: '政治面貌不能为空', trigger: 'blur' }]">
                    <el-input v-model="form.politicalAffiliation" />
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="出生日期" prop="birthDate"
                    :rules="[{ required: true, message: '出生日期不能为空', trigger: 'blur' }]">
                    <el-date-picker v-model="form.birthDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="民族" prop="nationality"
                    :rules="[{ required: true, message: '民族不能为空', trigger: 'blur' }]">
                    <el-input v-model="form.nationality" />
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter="20">
            <el-col :span="8">
                <el-form-item label="婚姻状况" prop="maritalStatus"
                    :rules="[{ required: true, message: '婚姻状况不能为空', trigger: 'blur' }]">
                    <el-select v-model="form.maritalStatus" placeholder="--婚姻状况--">
                        <el-option label="未婚" value="未婚" />
                        <el-option label="已婚" value="已婚" />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="籍贯" prop="nativePlace"
                    :rules="[{ required: true, message: '籍贯不能为空', trigger: 'blur' }]">
                    <el-input v-model="form.nativePlace" />
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="家庭住址" prop="homeAddress"
                    :rules="[{ required: true, message: '家庭住址不能为空', trigger: 'blur' }]">
                    <el-input v-model="form.homeAddress" />
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter="20">
            <el-col :span="8">
                <el-form-item label="联系电话" prop="telephone"
                    :rules="[{ required: true, message: '联系方式不能为空', trigger: 'blur' }]">
                    <el-input v-model="form.telephone" />
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="QQ号" prop="qq">
                    <el-input v-model="form.qq" />
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="班级" prop="className"
                    :rules="[{ required: true, message: '班级不能为空(没分班就是1班)！', trigger: 'blur' }]">
                    <el-input v-model="form.className" />
                </el-form-item>
            </el-col>
        </el-row>

        <!-- 学籍信息 -->
        <el-row :gutter="20">
            <el-col :span="8">
                <el-form-item label="学院" prop="college"
                    :rules="[{ required: true, message: '学院不能为空', trigger: 'blur' }]">
                    <el-input v-model="form.college" />
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="专业" prop="major" :rules="[{ required: true, message: '专业不能为空', trigger: 'blur' }]">
                    <el-input v-model="form.major" />
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="学号" prop="studentId" :rules="[
                    { required: true, message: '学号不能为空', trigger: 'blur' },
                    { max: 14, min: 12, message: '学号格式可能有误', trigger: 'blur' }
                ]">
                    <el-input v-model="form.studentId" />
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter="20">
            <el-col :span="8">
                <el-form-item label="入伍日期" prop="joinArmyDate"
                    :rules="[{ required: true, message: '入伍日期不能为空', trigger: 'blur' }]">
                    <el-date-picker v-model="form.joinArmyDate" type="date" placeholder="选择日期"
                        value-format="YYYY-MM-DD" />
                </el-form-item>
            </el-col>
        </el-row>

        <el-col :span="8">
            <el-form-item label="个人照片" prop="profilePicture"
                :rules="[{ required: true, message: '照片不能为空！', trigger: 'blur' }]">
                <el-upload class="avatar-uploader" :show-file-list="false" :http-request="handleUpload"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="form.profilePicture" :src="form.profilePicture" class="avatar" ref="avatarImage" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-col>

        <!-- 选填内容 -->
        <el-collapse>
            <el-collapse-item title="选填内容 (点击展开)">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="身高 (米)" prop="height">
                            <el-input v-model="form.height" type="number" :step="0.1" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="体重 (千克)" prop="weight">
                            <el-input v-model="form.weight" type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="视力" prop="vision">
                            <el-input v-model="form.visionLeft" style="width: 45%;" type="number" :step="0.1"
                                placeholder="左眼" />
                            <el-input v-model="form.visionRight" style="width: 45%; margin-left: 10%;" type="number"
                                :step="0.1" placeholder="右眼" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="军种" prop="militaryBranch">
                            <el-select v-model="form.militaryBranch" placeholder="--军种--">
                                <el-option label="陆军" value="1" />
                                <el-option label="海军" value="2" />
                                <el-option label="空军" value="3" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="部队编号" prop="unitNumber">
                            <el-input v-model="form.unitNumber" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="军衔" prop="rankname">
                            <el-input v-model="form.rankname" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="第一次报名应征日期" prop="firstEnlistmentDate">
                            <el-date-picker v-model="form.firstEnlistmentDate" type="date" placeholder="选择日期"
                                value-format="YYYY-MM-DD" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="入伍地点" prop="enlistmentPlace">
                            <el-input v-model="form.enlistmentPlace" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="军事专业" prop="militarySpecialty">
                            <el-input v-model="form.militarySpecialty" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="军事职务" prop="militaryPosition">
                            <el-input v-model="form.militaryPosition" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-collapse-item>
        </el-collapse>

        <!-- 剪切对话框 -->
        <el-dialog v-model="cropDialogVisible" title="剪切照片" width="30%">
            <div class="cropper-container">
                <img ref="cropperImage" :src="tempImageUrl" alt="Cropper Image" />
            </div>
            <template #footer>
                <el-button @click="cropDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="cropImage">确认</el-button>
            </template>
        </el-dialog>

        <el-form-item class="form-buttons">
            <el-button class="submit-btn" type="primary" @click="onSubmit">
                <img src="../../assets/icons/submit.svg" alt="icon"
                    style="width: 18px; height: 18px; margin-right: 6px;" />
                提交
            </el-button>
            <el-button @click="onCancel">取消</el-button>
            <el-button type="danger" @click="onClear">
                <img src="../../assets/icons/begin.svg" alt="icon"
                    style="width: 18px; height: 18px; margin-right: 5px;" />
                初始态
            </el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref, nextTick, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElForm } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import Cropper from 'cropperjs'
import { upLodaImg, transformMember } from '@/api/join-army/join-army'
import 'cropperjs/dist/cropper.css'

const props = defineProps({
    memberInfo: {
        type: Object,
        required: true
    },
    currentIndex: {
        type: Number,
        required: true
    },
    totalMembers: {
        type: Number,
        required: true
    },
    type: {
        type: String,
        required: true
    }
});

//动态判断是预储还是预征
const title = props.type === 'preReserve' ? '预储成员' : '预征班成员';

//挂载时处理视力
onMounted(() => {
    if (form.vision != null && form.vision.includes('_')) {
        const [left, right] = form.vision.split('_');
        form.visionLeft = left || ''; // 避免 undefined
        form.visionRight = right || ''; // 避免 undefined
    } else {
        form.visionLeft = '';
        form.visionRight = '';
    }
});

const form = reactive({
    name: props.memberInfo.name,
    gender: props.memberInfo.gender == 1 ? '男' : '女',
    profilePicture: props.memberInfo.profilePicture,
    idCard: props.memberInfo.idCard,
    politicalAffiliation: props.memberInfo.politicalAffiliation,
    birthDate: props.memberInfo.birthDate,
    nationality: props.memberInfo.nationality,
    maritalStatus: props.memberInfo.maritalStatus == 1 ? '已婚' : '未婚',
    nativePlace: props.memberInfo.nativePlace,
    homeAddress: props.memberInfo.homeAddress,
    telephone: props.memberInfo.telephone,
    qq: props.memberInfo.qq,
    joinArmyDate: props.memberInfo.joinArmyDate,
    college: props.memberInfo.college,
    major: props.memberInfo.major,
    studentId: props.memberInfo.studentId,
    grade: props.memberInfo.grade,
    className: props.memberInfo.className,
    height: props.memberInfo.height,
    weight: props.memberInfo.weight,
    visionLeft: props.memberInfo.visionLeft,
    visionRight: props.memberInfo.visionRight,
    vision: props.memberInfo.vision,
    militaryBranch: props.memberInfo.militaryBranch,
    unitNumber: props.memberInfo.unitNumber,
    rankname: props.memberInfo.rankname,
    firstEnlistmentDate: props.memberInfo.firstEnlistmentDate,
    enlistmentPlace: props.memberInfo.enlistmentPlace,
    militarySpecialty: props.memberInfo.militarySpecialty,
    militaryPosition: props.memberInfo.militaryPosition,
});

// 监听 visionLeft 和 visionRight
watch(
    () => [form.visionLeft, form.visionRight],
    ([left, right]) => {
        form.vision = `${left || ''}_${right || ''}`;
    }
);

const tempImageUrl = ref('') // 临时图片地址，用于裁剪
const cropDialogVisible = ref(false) // 控制裁剪对话框显示
const formRef = ref<InstanceType<typeof ElForm>>()
const avatarImage = ref<HTMLImageElement | null>(null)
const cropperImage = ref<HTMLImageElement | null>(null)
let cropper: Cropper | null = null
let uploadFile: File | null = null // 保存上传的文件

// 自定义上传方法
const handleUpload = async (options: any) => {
    const { file } = options
    uploadFile = file
    tempImageUrl.value = URL.createObjectURL(file)
    cropDialogVisible.value = true
    nextTick(() => {
        if (cropperImage.value) {
            cropper = new Cropper(cropperImage.value, {
                aspectRatio: 1 / 1.4, // 设置宽高比为1:1.4
                viewMode: 1,
                autoCropArea: 1,
            })
        }
    })
}

// 图片上传前的校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('照片格式必须为JPG或PNG!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('照片大小不能超过2MB!')
        return false
    }
    return true
}

// 裁剪图片
const cropImage = async () => {
    if (cropper) {
        const croppedCanvas = cropper.getCroppedCanvas({
            width: 100, // 输出宽度
            height: 140, // 输出高度
        })
        croppedCanvas.toBlob(async (blob) => {
            if (blob) {
                // 将裁剪后的图片转换为 File 对象
                const croppedFile = new File([blob], uploadFile?.name || 'cropped-image.jpg', {
                    type: 'image/jpeg',
                })

                // 上传裁剪后的图片
                // 上传裁剪后的图片
                try {
                    const formData = new FormData()
                    formData.append('file', croppedFile)
                    const url = '/admin/common/upload';
                    const config = {
                        headers: {
                            'Content-Type': 'multipart/form-data',
                        },
                    }
                    const response = await upLodaImg(url, formData, config);

                    // 上传成功，显示图片
                    form.profilePicture = response.data // 假设返回的数据中有 url 字段
                    ElMessage.success('图片上传成功!')
                } catch (error) {
                    ElMessage.error('图片上传失败，请重试')
                }

                // 关闭裁剪对话框
                cropDialogVisible.value = false
                cropper.destroy()
                cropper = null
            }
        }, 'image/jpeg')
    }
}

const onSubmit = () => {
    formRef.value?.validate((valid) => {
        if (valid) {
            console.log('Form Data:', form)
            submitInfo();//提交信息给后端
            formRef.value?.resetFields(); // 清空当前表单
            emit('submit', form) // 触发父组件提交事件
        } else {
            ElMessage.error('请填写完整信息')
        }
    })
}

// 定义事件
const emit = defineEmits(['submit', 'cancel'])

//上传提交
function submitInfo() {
    const data = {
        joinArmyInfoDTO: form,
        type: props.type
    };
    transformMember(data).then(r => {
        ElMessage.success('提交成功!')
    }).catch(error => {
        ElMessage.error('提交失败' + error);
    });
}

// 清空功能
const onClear = () => {
    formRef.value?.resetFields();
    localStorage.removeItem('tempFormData');
    ElMessage.success('已撤销到原始信息！');
}

// 取消功能
const onCancel = () => {
    ElMessageBox.confirm('退出将导致数据丢失，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        formRef.value?.resetFields(); // 清空表单
        emit('cancel'); // 触发父组件取消事件
    }).catch(() => {
        // 用户点击了取消，继续填写
    });
}

</script>

<style scoped>
* {
    margin: 0;
    padding: 0;
}

.header-title {
    font-size: large;
    justify-self: center;
    margin-bottom: 10px;
    margin-top: -15px;
}

.header-icon {
    width: 24px;
    height: 24px;
    margin-right: 8px;
    margin-bottom: -4px;
}

/* 提交按钮 */
.submit-btn {
    background-color: #4caf50;
}

.submit-btn:hover {
    background-color: #45a049;
}

.form-container {
    padding: 20px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    background-color: #fff;
}

.el-form-item {
    margin-bottom: 17px;
    justify-content: center;
}

.form-buttons {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    width: 100%;
    /* 确保宽度占满父容器 */
    margin-bottom: -5px;
}

.el-button {
    margin-right: 10px;
    padding: 10px;
    width: 75px;
}

.avatar-uploader .avatar {
    width: 100px;
    height: 140px;
    display: block;
    object-fit: cover;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 140px;
    text-align: center;
    border-style: dotted;
}

.cropper-container {
    width: 100%;
    height: 300px;
}
</style>

<style>
.form-buttons {
    .el-form-item__content {
        justify-content: center;
    }
}

.el-collapse-item {
    .el-collapse-item__content {
        padding-bottom: 0;
    }
}
</style>